import { defineStore } from 'pinia'
import { IProduct, buyProducts } from '@/api/shop'
// 引入products
import { useProductsStore } from '@/store/products'
type CartProduct = {
  quantity: number
} & Omit<IProduct, 'inventory'>
export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      // 购物车商品列表
      cartList: [] as CartProduct[],
      // 结算结果
      checkoutState: null as null | string
    }
  },
  getters: {
    totalPrice(state): number {
      return state.cartList.reduce((total, item) => {
        return total + item.price * item.quantity
      },0)
    }
  },
  actions: {
    // 添加商品
    addProductToCart(product: IProduct) {
      // 1. 是否有库存
      if (product.inventory < 1) return
      // 2. 是否已经有同类商品
      const cartItem  = this.cartList.find(item => product.id === item.id)
      if (cartItem) {
        cartItem.quantity++
      } else {
        this.cartList.unshift({
          id: product.id,
          title: product.title,
          price: product.price,
          quantity: 1
        })
      }
      // 更新库存
      const productStore = useProductsStore()
      productStore.decrementProduct(product)
    },
    // 结算
    async checkout() {
      const res = await buyProducts()
      this.checkoutState = res ? '成功' : '失败'
    }
  },
  persist: {
    enabled: true,
    /* strategies: [
      {
        key: 'cart',
        storage: localStorage
      }
    ] */
  }
})